package com.nightsoul.springboottest2.shiro.realm;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.hash.Hashing;
import com.nightsoul.springboottest2.domain.SysPermission;
import com.nightsoul.springboottest2.domain.SysRole;
import com.nightsoul.springboottest2.domain.SysUser;
import com.nightsoul.springboottest2.service.SysUserService;

public class MyJdbcRealm extends AuthorizingRealm {
	private static final Logger LOGGER = LoggerFactory.getLogger(MyJdbcRealm.class);

	@Resource
	private SysUserService sysUserService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		LOGGER.info("MyJdbcRealm.doGetAuthorizationInfo()");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
		for(SysRole sysRole : sysUser.getRoles()) {
			authorizationInfo.addRole(sysRole.getRole());
			for(SysPermission sysPermission : sysRole.getPermissions()) {
				authorizationInfo.addStringPermission(sysPermission.getPermission());
			}
		}

		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		LOGGER.info("MyJdbcRealm.doGetAuthenticationInfo()");
		String username = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());
		LOGGER.info(token.getCredentials().toString());
		SysUser sysUser = this.sysUserService.findByUsername(username);
		if(sysUser == null /*|| !sysUser.getPassword().equals(password)*/) {
			throw new AuthenticationException();
		}

		String encodingPassword = Hashing.md5().hashBytes(password.getBytes()).toString();
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		usernamePasswordToken.setPassword(encodingPassword.toCharArray());
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
			sysUser,
			sysUser.getPassword(),
			ByteSource.Util.bytes(sysUser.getCredentialsSalt()),
			super.getName()
		);
		return authenticationInfo;
	}

}
